<?php
require('../includes/init.php');
require(ROOT_PATH . '/includes/lib_array.php');
require(ROOT_PATH . '/includes/lib_order.php');
$act = (isset($_REQUEST['act']) && $_REQUEST['act'] <> '') ? $_REQUEST['act'] : 'addToCart';
if ($act == 'AddToCart')
{
	header('Content-type:application/json');
    $rs_arr = array(
        'type' => '0',
        'msg'  => ''
    );
	$pid = isset($_POST['pid'])?(int)$_POST['pid']:0;
	if($pid == 0)
	{
		$rs_arr = array(
        	'type' => '0',
            'msg'  => '产品ID不正确'
        );
        die(json_encode($rs_arr));
	}
	$sql = "SELECT * FROM `product_detail` WHERE `pd_id`='".$pid."' AND `is_show`='1';";
	$gg = $db->getRow($sql);
	if(empty($gg))
	{
		$rs_arr = array(
        	'type' => '0',
            'msg'  => '该产品规格不存在，或者已经下架'
        );
        die(json_encode($rs_arr));
	}
	$sql = "SELECT * FROM `cart` WHERE `product_id`='".$gg['product_id']."' AND `pd_id`='".$pid."' AND `session_id`='".$_SESSION[SESSION_PREFIX]['session_id']."';";
	$row = $db->getRow($sql);
	if(!empty($row))
	{
		$pnum = intval($_POST['pcount'])+intval($row['pcount']);
		if($gg['is_stocklast']==1 && $pnum > $gg['stock'])
		{
			$kemai_count = $gg['stock']-$row['pcount'];
			$rs_arr = array(
				'type' => '0',
				'msg'  => '<b>清仓产品，售完为止。</b><br>目前库存只有'.$gg['stock'].'件，您购物车已经有 '.$row['pcount'].' 件了，您最大只能再购买 '.$kemai_count.' 件。'
			);
			die(json_encode($rs_arr));
		}
		
		$price = get_price($gg, $pnum);

		$sql = "UPDATE `cart` SET `price`='".$price."',`pcount`=".$pnum.",`update_tm`=NOW() WHERE `product_id`='".$gg['product_id']."' AND `pd_id`='".$pid."' AND `session_id`='".$_SESSION[SESSION_PREFIX]['session_id']."';";
	}
	else
	{
		$pnum = intval($_POST['pcount']);
		$price = get_price($gg, $pnum);
		$sql = "INSERT INTO `cart` SET `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."',`session_id`='".$_SESSION[SESSION_PREFIX]['session_id']."',`product_id`='".$gg['product_id']."', `pd_id`='".$pid."',`price`='".$price."',`pcount`='".$pnum."',`pkg`='".$_POST['pkg']."',`add_tm`=NOW(),`update_tm`=NOW();";
	}
	if($db->query($sql))
	{
		$sql = "SELECT count(*) as pnum,SUM(`pcount`) as pcount FROM `cart` WHERE `session_id`='".$_SESSION[SESSION_PREFIX]['session_id']."';";
  		$cart_info = $db->getRow($sql);
		
		$rs_arr = array(
        	'type' => '1',
			'url'  => '/cart/',
			'pnum' => $cart_info['pnum'],
			'ggnum' => $cart_info['pcount'],
            'msg'  => '加入购物车成功。<br>您可以直接进入购物车结算或者继续购买？'
        );
        die(json_encode($rs_arr));
	}
	else
	{
		$rs_arr = array(
        	'type' => '0',
            'msg'  => '加入购物车失败'
        );
        die(json_encode($rs_arr));
	}

}elseif ($act == 'ShopcartUpdateNumber')
{
	header('Content-type:application/json');
    $rs_arr = array(
        'type' => '0',
        'msg'  => ''
    );
	$ids = $_POST['ids'];
    $ids =array_filter(explode(",", $ids));
	$pid = isset($_POST['pid'])?(int)$_POST['pid']:0;
	if($pid == 0)
	{
		$rs_arr = array(
			'type' => '0',
			'msg'  => '错误的产品ID'
		);
		die(json_encode($rs_arr));
	}
	$pcount = isset($_POST['pcount'])?intval($_POST['pcount']):0;
	if($pcount <= 0)
	{
		$rs_arr = array(
			'type' => '0',
			'msg'  => '产品数量不能为0，不需要该产品了，请删除！'
		);
		die(json_encode($rs_arr));
	}
	$sql = "SELECT * FROM `product_detail` WHERE `pd_id`='".$pid."';";
	$gg = $db->getRow($sql);
	if(empty($gg))
	{
		$rs_arr = array(
			'type' => '0',
			'msg'  => '产品不存在'
		);
		die(json_encode($rs_arr));
	}
	$sql = "SELECT * FROM `product` WHERE `product_id`='".$gg['product_id']."'";
	$product = $db->getRow($sql);
	if($gg['is_stocklast']=='1' && $pcount>$gg['stock'])
	{
		$pcount = $gg['stock'];
		$lstock = "售完即止";
	}
	else
	{
		$lstock = $gg['stock']>=$pcount?"现货":"部分现货";
	}
	$decimals = $product['bigcate_id']=='1'?4:2;
	$price = get_price($gg, $pcount, $decimals);
	$ltotal = $pcount*$price;
	$ggnum = 0;
	$sql = "UPDATE `cart` SET `pcount`=".intval($pcount).",`price`='".$price."',`update_tm`=NOW() WHERE `pd_id`='".$pid."' AND `session_id`='".$_SESSION[SESSION_PREFIX]['session_id']."';";
	if($db->query($sql))
	{
		//$cart_list = cart_goods($_SESSION[SESSION_PREFIX]['session_id'], 1);
		$cart_all_goods = cart_goods($_SESSION[SESSION_PREFIX]['session_id']);

		$cart_list = [];
		foreach($cart_all_goods as $cart_item){
			if(in_array($cart_item["cart_id"], $ids)){
				$cart_list[] = $cart_item;
			}
		}

		$total = order_fee($cart_list);
		$decimals = $product['bigcate_id']=='1'?4:2;
		$price = price_format($price, false, $decimals);
		
		$rs_arr = array(
			'type' 			=> '1',
			'msg'  			=> '更新成功',
			'pcount' 		=> $pcount,
			'price' 		=> $price,
			'ltotal' 		=> $ltotal,
			'lstock' 		=> $lstock,
			'ggnum'         => $total['total_num'],
			'goods_price' 	=> $total['goods_price'],
			'pack_fee' 		=> $total['pack_fee'],
			'pay_fee' 		=> $total['pay_fee'],
			'shipping_fee' 	=> $total['shipping_fee'],
			'insure_fee' 	=> $total['insure_fee'],
			'discount' 		=> $total['discount'],
			'total_fee'		=> $total['total_fee'],
		);
		die(json_encode($rs_arr));
	}
	else
	{
		$rs_arr = array(
			'type' => '0',
			'msg'  => '更新出错'
		);
		die(json_encode($rs_arr));
	}
}
elseif ($act == 'ShopcartUpdateCheckbox'){
    header('Content-type:application/json');
    $ids = $_POST['ids'];
    $ids = explode(",", $ids);

    $cart_list = cart_goods($_SESSION[SESSION_PREFIX]['session_id']);
    $cart_data = [];
    foreach($cart_list as $cart_item){
        if(in_array($cart_item["cart_id"], $ids)){
            $cart_data[] = $cart_item;
        }
    }
    $total = order_fee($cart_data);
    
    $rs_arr = array(
        'type' 			=> '1',
        'msg'  			=> '更新成功',
        'ggnum'         => $total['total_num'],
        'goods_price' 	=> $total['goods_price'],
        'pack_fee' 		=> $total['pack_fee'],
        'pay_fee' 		=> $total['pay_fee'],
        'shipping_fee' 	=> $total['shipping_fee'],
        'insure_fee' 	=> $total['insure_fee'],
        'discount' 		=> $total['discount'],
        'total_fee'		=> $total['total_fee'],
    );
    die(json_encode($rs_arr));
}
elseif ($act == 'loadMiniCart')
{
	header('Content-type:application/json');
    $rs_arr = array(
        'ischange' => '0'
    );
	$hscs = $_POST['hscs'];
	$hs_arr = explode(',', $hscs);
	foreach($hs_arr as $k => $v)
	{
		$kv = explode(':', $v);
		$old_pd_ids[] = $kv[0];
		$old_gg_nums[] = $kv[1];
	}
	
	$cart_list = cart_goods($_SESSION[SESSION_PREFIX]['session_id']);
	$total = order_fee($cart_list);
	$total_num = 0;
	
	$nscs = array_to_hashmap($cart_list, 'pd_id', 'pcount');
	$pd_ids = array_keys($nscs);
	$gg_nums = array_values($nscs);
	
	$pnum = count($cart_list);
	$ggnum = 0;
	$nav_cur_val = '';
	
	$scdetail = '';
	
	if(!empty($cart_list))
	{
		$scdetail = '<div class="exlist">';
		foreach($cart_list as $key => $cart)
		{
			$sql = "SELECT * FROM `product` WHERE `product_id`='".$cart['product_id']."';";
			$product = $db->getRow($sql);
			$sql = "SELECT * FROM `product_pic` WHERE `product_id`='".$cart['product_id']."' LIMIT 1;";
			$pic = $db->getRow($sql);
			$pic_url = $pic['pic100']<>''?$pic['pic100']:'/none.jpg';
			$sql = "SELECT * FROM `product_detail` WHERE `pd_id`='".$cart['pd_id']."';";
			$gg = $db->getRow($sql);
			$ggnum += $cart['pcount'];
			$nav_cur_val .= $nav_cur_val=='' ? $cart['pd_id'].':'.$cart['pcount'] : ','.$cart['pd_id'].':'.$cart['pcount'];
			
			$scdetail .= '<ul id="nav_pdid_'.$gg['pd_id'].'"><li class="ex1"><a href="/product/'.$product['product_id'].'.html" title="'.$product['title'].'"><img src="/upload'.$pic_url.'" onerror="this.src=\'/images/none.jpg\'" alt="'.$product['title'].'"></a></li><li class="ex2"><div class="exc2"><font color="#999999"><a href="/product/'.$product['product_id'].'.html" title="'.$product['title'].'"><b>'.$product['title'].'</b></a><br>零件号：</font><a href="/product'.$product['product_id'].'.html" title="'.$product['title'].'">'.yjt_id($gg['pd_id']).'</a>&nbsp;&nbsp;<font color="#999999">规格：</font>'.$gg['xy_value'].'</div></li><li class="ex3"><div class="exc2"><div><span>'.price_format($cart['price']).'</span>×'.$cart['pcount'].'</div><div><span>&nbsp;</span></div><div><a href="javascript:void(0);" class="scdel-btn" data-id="'.$cart['pd_id'].'">删除</a></div></div></li></ul>';
		}
		$scdetail .= '</div>'; 
		$scdetail .= '<div class="excalc" id="nav_total"><div style="margin-right:8px;">'.$pnum.'种商品'.intval($ggnum).'件，合计<strong>'.price_format($total['goods_price']).'</strong></div></div>';
		$scdetail .= '<div class="exbtn"><a href="/cart/">去购物车结算>></a></div>';
	}
	else
	{
		$pnum = 0;
		$ggnum = 0;
		$scdetail = '<label>购物车中没有商品，快去选购吧！</label>';
	}
	
	$df_ids = array_diff($pd_ids, $old_pd_ids);
	$df_nums = array_diff($gg_nums, $old_gg_nums);
	
	if(empty($df_ids) && empty($df_nums))
	{
		$rs_arr = array(
			'ischange' => '0'
		);
	}
	else
	{
		$rs_arr = array(
			'ischange' => '1',
			'scdetail' => $scdetail,
			'pnum' => $pnum,
			'ggnum' => $ggnum,
			'nscs' => $nav_cur_val
		);
	}
	die(json_encode($rs_arr));
}
elseif ($act == 'delFromMiniCart')
{
	header('Content-type:application/json');
    $rs_arr = array(
        'type' => '0',
        'msg'  => ''
    );
	//删除
	$sql = "DELETE FROM `cart` WHERE `pd_id`='".$_POST['pid']."' AND `session_id`='".$_SESSION[SESSION_PREFIX]['session_id']."';";
	$db->query($sql);
	
	$cart_list = cart_goods($_SESSION[SESSION_PREFIX]['session_id']);
	$total = order_fee($cart_list);
	$total_num = 0;//总的数量
	
	$pnum = count($cart_list);//产品数量
	$ggnum = 0;//具体规格数量
	$nav_cur_val = '';//设置input的值
	$scdetail = '';
	$nav_total = '';
	//计算基本信息
	if(!empty($cart_list))
	{
		foreach($cart_list as $key => $cart)
		{
			//产品数量
			$ggnum += $cart['pcount'];
			$nav_cur_val .= $nav_cur_val=='' ? $cart['pd_id'].':'.$cart['pcount'] : ','.$cart['pd_id'].':'.$cart['pcount'];
		}
	}
	else
	{
		$pnum = 0;
		$ggnum = 0;
		$scdetail = '<label>购物车中没有商品，快去选购吧！</label>';
	}
	
	if($pnum>0)
	{
		$nav_total = '<div style="margin-right:8px;">'.$pnum.'种商品'.intval($ggnum).'件，合计<strong>'.price_format($total['goods_price']).'</strong></div>';
		$rs_arr = array(
			'type' => '1',
			'nav_total' => $nav_total,
			'pnum' => $pnum,
			'ggnum' => $ggnum,
			'nscs' => $nav_cur_val
		);
	}
	else
	{
		$rs_arr = array(
			'type' => '2',
			'scdetail' => $scdetail,
			'pnum' => $pnum,
			'ggnum' => $ggnum,
			'nscs' => $nav_cur_val
		);
	}
	die(json_encode($rs_arr));
}
//购物车页面的删除
elseif ($act == 'DelCurrent')
{
	header('Content-type:application/json');
    $rs_arr = array(
        'type' => '0',
        'msg'  => ''
    );
	//删除
	$sql = "DELETE FROM `cart` WHERE `pd_id`='".$_POST['pid']."' AND `session_id`='".$_SESSION[SESSION_PREFIX]['session_id']."';";
	$db->query($sql);
	
	//读取现在的
	$cart_list = cart_goods($_SESSION[SESSION_PREFIX]['session_id']);
	$total = order_fee($cart_list);
	$total_num = 0;//总的数量
	
	$pnum = count($cart_list);//产品数量
	$ggnum = 0;//具体规格数量
	//计算基本信息
	if(!empty($cart_list))
	{
		foreach($cart_list as $key => $cart)
		{
			//产品数量
			$ggnum += $cart['pcount'];
		}
	}
	else
	{
		$pnum = 0;
	}
	
	if($pnum>0)
	{
		$rs_arr = array(
			'type' => '1',
			'pnum' => $pnum,
			'ggnum' => $ggnum,
			'pta' => $total['goods_price'],
			'pda' => $total['discount'],
			'scpf' => $total['shipping_fee'],
			'scpot' => $total['goods_price']-$total['discount']+$total['shipping_fee']
		);
	}
	else
	{
		$rs_arr = array(
			'type' => '2'
		);
	}
	die(json_encode($rs_arr));
}
//ShopcartDeleteSelected
elseif ($act == 'ShopcartDeleteSelected')
{
	header('Content-type:application/json');
    $rs_arr = array(
        'type' => '0',
        'msg'  => ''
    );
	$pids_arr = explode(',', $_POST['pids']);
	$sql = "DELETE FROM `cart` WHERE `pd_id` ".db_create_in($pids_arr)." AND `session_id`='".$_SESSION[SESSION_PREFIX]['session_id']."';";
	$db->query($sql);
	
	$cart_list = cart_goods($_SESSION[SESSION_PREFIX]['session_id']);
	$total = order_fee($cart_list);
	$total_num = 0;//总的数量
	
	$pnum = count($cart_list);//产品数量
	$ggnum = 0;//具体规格数量
	if(!empty($cart_list))
	{
		foreach($cart_list as $key => $cart)
		{
			//产品数量
			$ggnum += $cart['pcount'];
		}
	}
	else
	{
		$pnum = 0;
	}
	
	if($pnum>0)
	{
		$rs_arr = array(
			'type' => '1',
			'pnum' => $pnum,
			'ggnum' => $ggnum,
			'pta' => $total['goods_price'],
			'pda' => $total['discount'],
			'scpf' => $total['shipping_fee'],
			'scpot' => $total['goods_price']-$total['discount']+$total['shipping_fee']
		);
	}
	else
	{
		$rs_arr = array(
			'type' => '2'
		);
	}
	die(json_encode($rs_arr));
}

elseif ($act == 'ShopcartClear')
{
	header('Content-type:application/json');
	//删除
	$sql = "DELETE FROM `cart` WHERE `session_id`='".$_SESSION[SESSION_PREFIX]['session_id']."';";
	if($db->query($sql))
	{
		$rs_arr = array(
			'type' => '1',
			'msg'  => '清空成功'
		);
	}
	else
	{
		$rs_arr = array(
			'type' => '0',
			'msg'  => '清空失败'
		);
	}
	die(json_encode($rs_arr));
}
elseif ($act == 'aaaaa')
{
	die($_POST['pids']);
}
elseif ($act == 'add2cart')
{
	header('Content-type:application/json');	
    $rs_arr = array(
        'type' => '0',
        'msg'  => ''
    );
	
	foreach($_POST['item_no'] as $key => $pid)
	{
		if($pid<>'')
		{
			$pcount = $_POST['qty'][$key];
			$sql = "SELECT * FROM `product_detail` WHERE `pd_id`='".$pid."' AND `is_show`='1';";
			$gg = $db->getRow($sql);
			if(!empty($gg))
			{
				$sql = "SELECT * FROM `cart` WHERE `product_id`='".$gg['product_id']."' AND `pd_id`='".$pid."' AND `session_id`='".$_SESSION[SESSION_PREFIX]['session_id']."';";
				$row = $db->getRow($sql);
				if(!empty($row))
				{
					$pnum = intval($pcount)+intval($row['pcount']);
					$price = get_price($gg, $pnum);
			
					$sql = "UPDATE `cart` SET `price`='".$price."',`pcount`=".$pnum.",`update_tm`=NOW() WHERE `product_id`='".$gg['product_id']."' AND `pd_id`='".$pid."' AND `session_id`='".$_SESSION[SESSION_PREFIX]['session_id']."';";
				}
				else
				{
					$pnum = intval($pcount);
					$price = get_price($gg, $pnum);
					$sql = "INSERT INTO `cart` SET `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."',`session_id`='".$_SESSION[SESSION_PREFIX]['session_id']."',`product_id`='".$gg['product_id']."', `pd_id`='".$pid."',`price`='".$price."',`pcount`='".$pnum."',`pkg`='".$gg['pkg']."',`add_tm`=NOW(),`update_tm`=NOW();";
				}
				if($db->query($sql))
				{
					$sql = "SELECT count(*) as pnum,SUM(`pcount`) as pcount FROM `cart` WHERE `session_id`='".$_SESSION[SESSION_PREFIX]['session_id']."';";
					$cart_info = $db->getRow($sql);
				}
			}
		}
	}	
	$rs_arr = array(
		'result' => 'true'
	);
	die(json_encode($rs_arr));
}
